/*
 * @Author: Lin Hongwei
 * @Date: 2022-10-18 00:30:02
 * @LastEditTime: 2022-10-25 12:27:45
 * @LastEditors: Lin Hongwei
 * @email: 1365755396@qq.com
 * @CSDN: https://blog.csdn.net/weixin_45429409
 * @Description: 统一成功和失败的响应
 * 使用高阶函数和函数柯里化
 */
const errHandle = (ctx = {}) => async (err = {}) => {
  let status = err.status || 500;
  switch (err.code) {
    case '10001':
      status = 400
      break
    case '10002':
      status = 409
      break
    case '10101':
      status = 401
      break
    case '10102':
      status = 401
      break
    default:
      status = 500
  }
  const message = typeof err == "string" ? err : err.message || "未知错误";
  ctx.status = status;
  ctx.response.body = {
    code: err.code || '10000',
    message
  }
}

const ResponseMiddleware = (option = {}) => async (ctx, next) => {
  ctx.success = async (data = []) => {
    ctx.type = option.type || 'json';
    ctx.status = option.code || 200;
    ctx.body = {
      code: ctx.status,
      message: option.successMsg || 'success',
      data
    }
  }
  // ctx.fail = (err = {}) => {

  // }
  ctx.fail = errHandle(ctx)
  await next()
};

module.exports = ResponseMiddleware;